import React, { createContext, useContext, useEffect, useState } from 'react';
import { IBelong, IFile, ISession, ITarget } from '@/ts/core';
import { command } from '@/ts/base';
import Directory from '@/components/Directory';
import DirectoryViewer from '@/components/Directory/views';
import TargetsActivity from '@/components/TargetActivity/TargetsActivity';
import { loadFileMenus } from '@/executor/fileOperate';
import ChatBody from './chat';
import { cleanMenus } from '@/utils/tools';
import Setting from './setting';
import WorkBench from './WorkBench';
import useAsyncLoad from '@/hooks/useAsyncLoad';
import { Button, Spin } from 'antd';
import PortalPage from './portal';
import AiAgent from './agent';
import FileIndex from './File';
import OnlineInfo from './online';
import TaskViewer from '@/components/NewWork';
import { useLocation } from 'react-router-dom';
import StoreDirectory from './store';

interface ISessionContext {
  updateContent: (newContent: string) => void;
}
const sessionContext = createContext<ISessionContext | undefined>(undefined);
// 提供自定义 hook
export const useSessionContext = () => {
  const context = useContext(sessionContext);
  if (!context) {
    throw new Error('useSessionContext must be used within a SessionContextProvider');
  }
  return context;
};
const SessionItem = ({ session, bodyType, height }: { session: ISession; bodyType: string; height?: string }) => {
  const [loaded] = useAsyncLoad(async () => {
    if (session.target.members.length < 30) {
      await session.target.loadMembers(false);
    }
  }, [session]);
  const [BodyType, setBodyType] = useState<string>(bodyType); //需要更新的状态
  const [visible, setVisible] = useState<boolean>(false); // 控制是否显示
  const location = useLocation(); // 获取当前路由信息
  useEffect(()=>{
    if(location.pathname === '/home' && bodyType !== 'relation') {
      setVisible(true); // 如果当前路由是 /home，则设置 visible 为 true
    }
    setBodyType(bodyType);
  },[bodyType])
    // 定义上下文的值
  const contextValue: ISessionContext = {
    updateContent: (newBodyType) => {
      console.log('父组件收到更新:', newBodyType);
      // 在这里更新父组件的状态或执行其他逻辑
      setBodyType(newBodyType);
    },
  };
  const RenderMemberDirectory: React.FC<{ target: ITarget }> = ({ target }) => {
    const [filter, setFilter] = useState('');
    const [content, setContent] = useState<IFile[]>(target.memberDirectory.content());
    useEffect(() => {
      target.subscribe(() => setContent(target.memberDirectory.content()));
      return () => {
        if (filter && filter.length > 0) {
          target.loadMembers(false);
        }
      };
    }, [target, filter]);
    return (
      <Spin spinning={!loaded}>
        {visible && <Button onClick={()=>{setBodyType('bench')}}>返回工作台</Button>}
        {loaded && (
          <DirectoryViewer
            extraTags={false}
            currentTag={'成员'}
            initTags={['成员']}
            selectFiles={[]}
            content={content}
            height={height}
            fileOpen={() => {}}
            contextMenu={(entity) => {
              const file = (entity as IFile) || target.memberDirectory;
              return {
                items: cleanMenus(loadFileMenus(file)) || [],
                onClick: ({ key }: { key: string }) => {
                  if (key === 'joinFriend') {
                    command.emitter('executor', key, target);
                  } else {
                    command.emitter('executor', key, file);
                  }
                },
              };
            }}
            onScrollEnd={async () => {
              if (target.memberFilterCount > target.members.length) {
                await target.loadMembers(false, filter);
                setContent([...target.memberDirectory.content()]);
              }
            }}
            onFilter={async (value) => {
              setFilter(value);
              await target.loadMembers(false, value);
              setContent([...target.memberDirectory.content()]);
            }}
          />
        )}
      </Spin>
    );
  };
  return (
    <sessionContext.Provider value={contextValue}>
      {(() => {
        switch (BodyType) {
          case 'online':
            return <OnlineInfo key={session.target.key} space={session.target.space} />;
          case 'chat':
            return <ChatBody key={session.target.key} chat={session} filter={''}  onBackToBench={() => {setBodyType('bench')}} visible={true}/>
          case 'activity':
            return <TargetsActivity target={session.target} />;
          case 'store':
            return <StoreDirectory session={session} />;
          case 'file':
            return <FileIndex key={session.target.key} target={session.target} />;
          case 'relation':
            return <RenderMemberDirectory target={session.target} />;
          case 'setting':
            return <Setting target={session.target} session={session} />;
          case 'bench':
            return <WorkBench space={session.target as IBelong} />;
          case 'home':
            return (
              <PortalPage
                key={session.target.key}
                target={session.target}
                space={session.target as IBelong}
                activity={session.activity}
              />
            );
          case 'smart':
            return <AiAgent key={session.target.key} manager={session.target.agentManager} />;
          case 'work':
            return (
              <TaskViewer
                space={session.target}
                targetMetadataId={session.target.metadata.id}
                // openTask={(task: any) => {
                //   command.emitter('executor', 'openTask', task);
                // }}
              />
            );
          default:
            return <></>;
        }
      })()}
    </sessionContext.Provider>
  );
};
export default SessionItem;
